package com.dr.photoedit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dr.photoedit.utils.Constants;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    /* 添加文字 */
    //private static final int PHOTO_ADD_TEXT_DATA = 3033;

    public static final String imagePath = Environment.getExternalStorageDirectory() + "/Test/Test.jpg";
    private TextView mPath;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPath = (TextView) findViewById(R.id.img_path);
        iv = (ImageView) findViewById(R.id.img);
    }

    private File photoFile;

    public void onCamera(View v) {
//        if (createFile()) {
//            //调取相机
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//捕捉图像
//            //intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//            //File out = new File(getPhotopath());
//            Uri uri = Uri.fromFile(photoFile);
//            // 获取拍照后未压缩的原图片，并保存在uri路径中
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//            startActivityForResult(intent, Constants.PHOTO_CAMERA);
//        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //File mCurrentPhotoFile = new File(Constants.imagePath);

        String fileDir = Environment.getExternalStorageDirectory() + "/Test/";
        File file = new File(fileDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        //String fileName = new Date().getTime() + ".jpg";
        String fileName = "Test" + ".jpg";
        String originCameraImgPath = fileDir + fileName;
        File mCurrentPhotoFile = new File(originCameraImgPath);

//        if (!mCurrentPhotoFile.exists()) {
//            try {
//                mCurrentPhotoFile.createNewFile();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(mCurrentPhotoFile));
        startActivityForResult(intent, Constants.PHOTO_CAMERA);
    }


    /**
     * 获取原图片存储路径
     */
    private String getPhotopath() {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory() + "/Test/";
        String imageName = "Test.jpg";
        File file = new File(pathUrl);
        if (!file.exists()) {
            file.mkdirs();
        }
        fileName = pathUrl + imageName;
        return fileName;
    }

    private boolean createFile() {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Toast.makeText(this, "SD卡不可用", Toast.LENGTH_SHORT).show();
            return false;
        }

        String fileDir = Environment.getExternalStorageDirectory() + "/Test/";
        File file = new File(fileDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        //String fileName = new Date().getTime() + ".jpg";
        String fileName = "Test" + ".jpg";
        String originCameraImgPath = fileDir + fileName;
        photoFile = new File(originCameraImgPath);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Activity.RESULT_OK) {
//            switch (requestCode) {
//                case Constants.REQUEST_CODE_GRAFFITI:
//                    onGraffitiResult(data);
//                    break;
//                case Constants.REQUEST_CODE_ADDTEXT:
//                    onAddTextResult(data);
//                    break;
//                case Constants.PHOTO_CAMERA:
//                    onCameraResult(data);
//                    break;
//            }
//        } else {
//            Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
//        }
        if (requestCode == Constants.REQUEST_CODE_GRAFFITI) {
//            if (data == null) {
//                return;
//            }
            if (resultCode == GraffitiActivity.RESULT_OK) {
                String path = data.getStringExtra(GraffitiActivity.KEY_IMAGE_PATH);
                if (TextUtils.isEmpty(path)) {
                    return;
                }
                Picasso.with(this).load(new File(path)).into((ImageView) findViewById(R.id.img));
                //ImageLoader.getInstance(this).display(findViewById(R.id.img), path);
                mPath.setText(path);
            } else if (resultCode == GraffitiActivity.RESULT_ERROR) {
                Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == Constants.PHOTO_CAMERA && resultCode == Activity.RESULT_OK) {//照相机返回

//            GraffitiActivity.startActivityForResult(MainActivity.this, imagePath, REQ_CODE_GRAFFITI);
//            Bitmap bitmap = getBitmapFromUrl(imagePath, 2228, 3264);
//            saveScalePhoto(bitmap);
//            iv.setImageBitmap(bitmap);
//            Picasso.with(this).load(new File(imagePath)).into((ImageView) findViewById(R.id.img));


            // 将图片路径photoPath传到所要调试的模块
//            Intent photoFrameIntent = new Intent(MainActivity.this, AddTextActivity.class);
//            photoFrameIntent.putExtra("camera_path", imagePath);
//            startActivityForResult(photoFrameIntent, Constants.REQUEST_CODE_ADDTEXT);
//
//            Bitmap bitmap = getBitmapFromUrl(imagePath, 2228, 3264);
//            saveScalePhoto(bitmap);
//            iv.setImageBitmap(bitmap);
//            mPath.setText(imagePath);

            Intent intent = new Intent(MainActivity.this, EditPhotoActivity.class);
            intent.putExtra("camera_path", imagePath);
            startActivity(intent);
            //Bitmap bitmap = getBitmapFromUrl(imagePath, 2228, 3264);
            //saveScalePhoto(bitmap);
            //startActivityForResult(intent, Constants.REQUEST_CODE_ADDTEXT);

        } else if (requestCode == Constants.REQUEST_CODE_ADDTEXT) {

//            String resultPath = data.getStringExtra("camera_path");
//            Bitmap resultBitmap = BitmapFactory.decodeFile(resultPath);
//            //pictureShow.setImageBitmap(resultBitmap);
//            iv.setImageBitmap(resultBitmap);

        }
    }

    //涂鸦返回
    private void onGraffitiResult(Intent data) {
        String path = data.getStringExtra(GraffitiActivity.KEY_IMAGE_PATH);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Picasso.with(this).load(new File(path)).into((ImageView) findViewById(R.id.img));
        mPath.setText(path);
    }

    //文字返回
    private void onAddTextResult(Intent data) {
        String resultPath = data.getStringExtra("camera_path");
        Bitmap resultBitmap = BitmapFactory.decodeFile(resultPath);
        //pictureShow.setImageBitmap(resultBitmap);
        iv.setImageBitmap(resultBitmap);
    }


    //照相返回
    private void onCameraResult(Intent data) {
        Intent photoFrameIntent = new Intent(MainActivity.this, EditPhotoActivity.class);
        photoFrameIntent.putExtra("camera_path", imagePath);
        startActivityForResult(photoFrameIntent, Constants.REQUEST_CODE_ADDTEXT);

        Bitmap bitmap = getBitmapFromUrl(imagePath, 2228, 3264);
        saveScalePhoto(bitmap);
        iv.setImageBitmap(bitmap);
        mPath.setText(imagePath);
    }

    /**
     * 根据路径获取图片资源（已缩放）
     */
    private Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 优化
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;

        // 按照固定宽高进行缩放
        if (mWidth <= mHeight) {
            scaleWidth = (float) (width / mWidth);
            scaleHeight = (float) (height / mHeight);
        } else {
            scaleWidth = (float) (height / mWidth);
            scaleHeight = (float) (width / mHeight);
        }
        // 按照固定大小对图片进行缩放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 回收
        bitmap.recycle();
        return newBitmap;
    }

    /**
     * 存储缩放的图片
     */
    private void saveScalePhoto(Bitmap bitmap) {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory().getPath() + "/Test/";
        //namePic = "p" + DateFormat.format("hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";

        //机型 + 批架次 +专业 + 时间
        // String name = DateFormat.format("yyyyMMddhhmmss", Calendar.getInstance(Locale.CHINA))+ ".jpg";
        String name = "Test" + ".jpg";
        FileOutputStream fos = null;
        File file = new File(pathUrl);
        Log.d("文件夹", pathUrl);
        file.mkdirs();// 创建文件夹
        fileName = pathUrl + name;
        try {
            fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
